package com.baorant.seckillbackservice.service;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@EnableBinding(IReceiverService.class)
public class ReceiverService {
	@Autowired
	private StringRedisTemplate template;
	
	@StreamListener("seckill_apply-exchange")
	public void onReceiver(byte[] msg) {
		String apply_msg = new String(msg);
		System.out.println("消费者收到消息:" + apply_msg);
		String tmp = apply_msg.substring(13, apply_msg.length());
		System.out.println(tmp);
		String arr[] = tmp.split(",");
		if(arr.length!=2) {
			System.out.println("消息格式不正确");
			return;
		}
		try {
			int goodsid = Integer.parseInt(arr[0].trim());
			String ticket= arr[1].trim();
			String result_key ="seckill.result." + ticket;
			//1,判断是否到达抢购开始时间
			if(!ifStart())
			{		
				System.out.println("处理结果：抢购活动尚未开始");
				//将结果写入Redis
				template.opsForValue().set(result_key, "抢购活动尚未开始，请耐心等候...");
				return;
			}
			if(!checkstock(goodsid)) {//库存不足
				System.out.println("处理结果：库存不足");
				//将结果写入Redis
				template.opsForValue().set(result_key, "库存不足...");				
			}
			else //抢购成功
			{
				System.out.println("处理结果：ok. result_key="+result_key);
				//将结果写入Redis
				template.opsForValue().set(result_key, "ok");	
				saveOrder2redis(ticket, goodsid);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}		
	}
	
	
	public boolean ifStart() {
		String starttime = template.opsForValue().get("seckill.starttime");
		System.out.println(starttime);
		SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 北京
		bjSdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置北京时区
		String strNow = bjSdf.format(System.currentTimeMillis());
		System.out.println("北京时间：" + strNow);
		if (starttime != null && strNow.compareTo(starttime) < 0)
			return false;
		return true;
	}
	
	public boolean checkstock(int goodsid) {
		long stock = template.boundValueOps("seckill.stock."+goodsid).decrement();
		if (stock > 0)
			return true;
		return false;
	}
	
	public void saveOrder2redis(String ticket, int goodsid) {
		// 拼接订单数据
		String value = ticket+","+goodsid+","+System.currentTimeMillis(); 
		System.out.println("saveOrder2redis:"+ value);
		long r =template.opsForList().rightPush("seckill.order", value);
		System.out.println("r:"+ r);
		// 验证数据是否真的保存了
		Long listSize = template.opsForList().size("seckill.order");
		System.out.println("listSize:"+ listSize);
	}
}
